import java.text.MessageFormat

class SidebarGenerator {
    static void main(String[] args) {
//        new File(".", 'haiku.txt').withWriter('utf-8') { writer ->
//            writer.writeLine 'Into the ancient pond'
//            writer.writeLine 'A frog jumps'
//            writer.writeLine 'Water’s sound!'
//        }

//        new File("E:\\code\\codedesign-vdoing\\docsify-doc\\docs\\document").eachFileRecurse {it-> println(it.getAbsolutePath())}
//        rootSidebar();
        generateSibar(new File("E:\\code\\codedesign-vdoing\\docsify-doc\\docs\\document"));
    }

    // 生成全局的sidebar
    static void rootSidebar() {
        var root = new File("E:\\code\\codedesign-vdoing\\docsify-doc\\docs");
        var sidebar = new File("E:\\code\\codedesign-vdoing\\docsify-doc\\docs\\_sidebar.md");
        if (sidebar.exists()) {
            sidebar.delete();
            sidebar.createNewFile();
        }
        var builder = new StringBuilder();
        root.eachFileRecurse { it ->
            if (it.isFile() && !it.name.contains("_sidebar") && !it.name.contains(".nojekyll")) {
                var path = it.getAbsolutePath().replace("E:\\code\\codedesign-vdoing\\docsify-doc\\docs", ".");
                // 空格转换为20%
                path = path.replaceAll(" ", "%20")
                var name = it.getName();
                println(path);
                if (name.endsWith("md")) {
                    name = name.replace(".md", "")
                    sidebar.withWriterAppend("utf-8", { writer -> writer.writeLine MessageFormat.format("[{0}]({1})  ", name, path) })
                }
            }
        };
    }

    // 删除子目录下的sidebar
    static void deleteSidebar() {
        // TODO
    }


    static void generateSibar(File file) {
        file.eachFileRecurse { it ->
            {
                if (it.isDirectory()) {
                    // 如果是路径则在该路径下创建一个 _sidebar.md，如果是存在就不创建了
                    File sideFile = new File(it.getAbsolutePath() + "/_sidebar.md")
                    if (sideFile.exists()) {
                        sideFile.delete();
                        sideFile.createNewFile()
                    } else {
                        sideFile.createNewFile()
                    }

                    it.listFiles().each {
                        subIt ->
                            if (subIt.isFile()) {
                                var name = subIt.getName()
                                name = name.replaceAll(" ", "%20")
                                var path = "./" + name
                                if (!name.startsWith("_sidebar"))
                                    sideFile.withWriterAppend("utf-8", {
                                        writer -> writer.writeLine MessageFormat.format("[{0}]({1})  ", name, path)
                                    })
                            }
                    }
                }
            }
        }
    }
}